import React, { Component } from 'react';
import { Button, Icon, Input, Table, message, Popconfirm, Modal, Form } from 'antd';
import cn from 'classnames';
import validatorCreator from '@util/validator-creator';
import PropTypes from 'prop-types';
import {
  getAssetIndustryList,
  addAssetIndustry,
  delAssetIndustry,
  updateAssetIndustry
} from '@api/asset';
import _ from 'lodash';
import './index.less';

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions as assetManageActions } from '../asset-manage/reducer';
const prefixCls = 'vulnerability-manage';

class IndustryManage extends Component {
  static propTypes = {
    loadAssetIndustry: PropTypes.func
  };
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      count: 0,
      addVisable: false,
      modalTitle: '',
      loading: false
    };
  }

  componentDidMount() {
    this.initAssetIndustriesData();
  }

  initAssetIndustriesData = () => {
    this.setState({ loading: true });
    getAssetIndustryList().then(res => {
      const list = _.get(res, 'data.data.list', []);
      const count = _.get(res, 'data.data.count', 0);
      this.setState({ list, count, loading: false });
    });
  };

  toogleModalVisable = (stat, type) => {
    this.setState({ addVisable: stat });
    !stat && this.props.form.resetFields();
    const modalTitle = type === 'add' ? '添加行业' : '编辑行业';
    this.setState({ modalTitle });
  };

  saveIndustry = () => {
    const { modalTitle } = this.state;
    const { form, loadAssetIndustry } = this.props;
    form.validateFields((err, data) => {
      if (err) {
        return;
      }
      const action = data._id
        ? updateAssetIndustry
        : data => addAssetIndustry(_.pick(data, 'name'));
      action(data)
        .then(() => {
          message.success(`${modalTitle}分类成功`);
          this.toogleModalVisable(false);
          form.resetFields();
          this.initAssetIndustriesData();
          loadAssetIndustry();
        })
        .catch(err => {
          message.error(err.message);
        });
    });
  };

  deleteIndustry = _id => {
    delAssetIndustry({ _id })
      .then(() => {
        message.success('删除行业信息成功');
        this.initAssetIndustriesData();
      })
      .catch(err => {
        message.error(err.message);
      });
  };

  EditIndustry = item => {
    const name = _.get(item, 'name');
    const { form } = this.props;
    if (name) {
      form.setFieldsValue(item, () => {
        this.toogleModalVisable(true, 'edit');
      });
    }
  };

  render() {
    const columns = [
      {
        title: '行业名称',
        dataIndex: 'name',
        width: '25%'
      },
      {
        title: '类型',
        dataIndex: 'system',
        render: system => (system ? '系统默认' : '自定义'),
        width: '30%',
        className: 'vulner-type'
      },
      {
        title: '操作',
        render: item => {
          const disabled = item.system;
          return (
            <div className={cn('opts-cell', { disabled })}>
              <Button
                type={'link'}
                disabled={disabled}
                className="edit"
                onClick={() => this.EditIndustry(item)}
              >
                编辑
              </Button>
              <Popconfirm
                placement="bottomRight"
                title={'删除行业后，资产中会同时清除该行业，确认删除该行业吗？'}
                disabled={disabled}
                onConfirm={() => this.deleteIndustry(item._id)}
                okText="确定"
                cancelText="取消"
              >
                <Button type={'link'} className="delete">
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        }
      }
    ];

    const { list, count, addVisable, modalTitle, loading } = this.state;
    const {
      form: { getFieldDecorator }
    } = this.props;

    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>行业管理</div>

        <div className={`${prefixCls}-operate`}>
          <div>
            <Button type="primary" onClick={() => this.toogleModalVisable(true, 'add')}>
              <Icon type="plus-circle" />
              添加行业
            </Button>
            <Modal
              maskClosable={false}
              className={cn(
                'vulnerability-manage-modal',
                'no-header-bottom-lines',
                'bottom-center',
                'padding-24'
              )}
              title={modalTitle}
              onOk={this.saveIndustry}
              onCancel={() => this.toogleModalVisable(false)}
              visible={addVisable}
            >
              <Form
                colon={false}
                labelAlign="left"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
              >
                <Form.Item hidden className="hidden-form-item">
                  {getFieldDecorator('_id')(<Input />)}
                </Form.Item>
                <Form.Item required label="行业名称" key="name">
                  {getFieldDecorator('name', {
                    rules: [
                      {
                        validator: validatorCreator('名称', {
                          required: true
                        })
                      },
                      {
                        max: 32,
                        message: '您输入的内容超过32个字符限制'
                      }
                    ]
                  })(<Input placeholder="请输入中文、英文、特殊字符或数字，不超过32个字符" />)}
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </div>
        <div>
          <div className={`${prefixCls}-header-count`}>共有 “{count}” 个 行业</div>
          <Table loading={loading} columns={columns} dataSource={list} />
        </div>
      </div>
    );
  }
}

IndustryManage.propTypes = {
  form: PropTypes.object
};

const mapStateToProps = state => {
  return {
    allIndustries: _.get(state, 'assetManage.allIndustries', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(assetManageActions, dispatch)
  };
};

const WrapFormIndustryManage = connect(
  mapStateToProps,
  mapDispatchToProps
)(Form.create()(IndustryManage));
export default WrapFormIndustryManage;
